package lib

import "strconv"

func init() {
	Probs = append(Probs, Problem{
		Num:         233,
		Discription: "<=n的数中1出现的次数",
		Level:       3,
		Labels: map[string]int{
			"数学":  1,
		},
	})
}

//计算每一位的1出现的次数
func CountDigitOne(n int) int {
	count := 0
	multiple := 1
	for multiple <= n {
		//当前位的数字
		digit := n/multiple - n/(multiple*10)*10
		//当前位左边的数字
		leftNum := n / (multiple * 10)
		//当前位右边的数字
		rightNum := n % multiple

		//把当前位换成1，<=n的数字的个数有多少(对应0，1，其它三种情况)
		if digit == 0 {
			count += leftNum * multiple
		} else if digit == 1 {
			count += leftNum*multiple + rightNum + 1
		} else {
			count += (leftNum + 1) * multiple
		}

		multiple *= 10
	}

	return count
}

//用字符串表示不耗脑子的写法
func DigitOneInNumber(num int) int {
	res := 0
	numStr := strconv.Itoa(num)
	multiple := 1
	for i := len(numStr) - 1; i >= 0; i-- {
		if numStr[i] == '0' {
			val, _ := strconv.Atoi(numStr[:i])
			res += val  * multiple
		} else if numStr[i] == '1' {
			str := numStr[:i] + numStr[i+1:]
			val, _ := strconv.Atoi(str)
			res += val + 1
		} else {
			val, _ := strconv.Atoi(numStr[:i])
			res += (val+1) * multiple
		}

		multiple *= 10
	}

	return res
}